<template>
  <view class="page-container" :style="{ paddingBottom: `calc(140rpx + ${safeAreaInsetBottom}px)` }">
    <!-- 页面内容 -->
    <slot></slot>
    
    <!-- 自定义tabbar -->
    <view class="custom-tabbar" :style="{ 
      background: 'rgba(255, 255, 255, 0.95)',
      bottom: `calc(20rpx + ${safeAreaInsetBottom}px)`
    }">
      <view 
        class="tabbar-item" 
        v-for="(item, index) in tabbarItems" 
        :key="index"
        @click="switchTab(item.pagePath)"
        :class="{ active: currentPath === item.pagePath }"
      >
        <view class="tabbar-icon">
          <u-icon 
            :name="currentPath === item.pagePath ? item.selectedIcon : item.icon" 
            :color="currentPath === item.pagePath ? actualThemeColor : '#999'" 
            size="22"
          ></u-icon>
        </view>
        <text 
          class="tabbar-text" 
          :style="{ color: currentPath === item.pagePath ? actualThemeColor : '#999' }"
        >{{ item.text }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import useSystemInfo from '../hooks/useSystemInfo';

export default {
  name: 'PageTabbar',
  props: {
    themeColor: {
      type: String,
      default: '#07c160'
    }
  },
  data() {
    const { safeAreaInsetBottom } = useSystemInfo();
    
    return {
      currentPath: '',
      tabbarBackground: 'rgba(255, 255, 255, 0.98)',
      tabbarItems: [
        {
          pagePath: '/pages/index/index',
          text: '首页',
          icon: 'home',
          selectedIcon: 'home-fill'
        },
        {
          pagePath: '/pages/user/user',
          text: '我的',
          icon: 'account',
          selectedIcon: 'account-fill'
        }
      ],
      cachedThemeColor: '#07c160',
      safeAreaInsetBottom
    };
  },
  watch: {
    // 监听主题色变化
    themeColor: {
      handler(newColor) {
        this.cachedThemeColor = newColor;
        // 将主题色保存到本地存储
        this.saveThemeColorToCache(newColor);
      },
      immediate: true
    }
  },
  methods: {
    // 切换tab
    switchTab(path) {
      if (this.currentPath === path) return;
      
      uni.navigateTo({
        url: path,
        fail: (err) => {
          console.error('导航失败:', err);
          // 如果导航失败，可能是因为已经在该页面上，尝试重定向
          uni.redirectTo({
            url: path,
            fail: (redirectErr) => {
              console.error('重定向也失败:', redirectErr);
            }
          });
        }
      });
    },
    
    // 获取当前页面路径
    getCurrentPath() {
      const pages = getCurrentPages();
      if (pages.length > 0) {
        const currentPage = pages[pages.length - 1];
        const route = '/' + currentPage.route;
        this.currentPath = route;
      }
    },
    
    // 从缓存中获取主题色
    getThemeColorFromCache() {
      try {
        // 获取当前用户的头像URL
        const userInfo = uni.getStorageSync('USER_INFO') || {};
        const avatarUrl = userInfo.avatarUrl;
        
        if (avatarUrl) {
          // 获取缓存的主题色
          const cachedThemeColors = uni.getStorageSync('THEME_COLORS') || {};
          if (cachedThemeColors[avatarUrl]) {
            // 使用缓存的主题色
            this.cachedThemeColor = cachedThemeColors[avatarUrl].mainColor;
            console.log('PageTabbar使用缓存的主题色:', this.cachedThemeColor);
            return this.cachedThemeColor;
          }
        }
        
        // 如果没有缓存或没有头像，使用props传入的主题色
        return this.themeColor;
      } catch (error) {
        console.error('获取缓存主题色失败:', error);
        return this.themeColor;
      }
    },
    
    // 保存主题色到缓存
    saveThemeColorToCache(color) {
      try {
        // 获取当前用户的头像URL
        const userInfo = uni.getStorageSync('USER_INFO') || {};
        const avatarUrl = userInfo.avatarUrl;
        
        if (avatarUrl) {
          // 获取缓存的主题色
          const cachedThemeColors = uni.getStorageSync('THEME_COLORS') || {};
          
          // 如果缓存中没有该头像的主题色，或者主题色已更新，则更新缓存
          if (!cachedThemeColors[avatarUrl] || cachedThemeColors[avatarUrl].mainColor !== color) {
            // 如果缓存中已有该头像的记录，只更新主题色
            if (cachedThemeColors[avatarUrl]) {
              cachedThemeColors[avatarUrl].mainColor = color;
            } else {
              // 否则创建新记录
              cachedThemeColors[avatarUrl] = {
                mainColor: color,
                gradientColor: `linear-gradient(45deg, ${color}, ${color})`,
                timestamp: Date.now()
              };
            }
            
            // 保存到本地存储
            uni.setStorageSync('THEME_COLORS', cachedThemeColors);
            console.log('PageTabbar保存主题色到缓存:', color);
          }
        }
      } catch (error) {
        console.error('保存主题色到缓存失败:', error);
      }
    },
    
    // 刷新主题色
    refreshThemeColor() {
      // 从缓存中获取主题色
      this.cachedThemeColor = this.getThemeColorFromCache();
    }
  },
  mounted() {
    this.getCurrentPath();
    // 从缓存中获取主题色
    this.cachedThemeColor = this.getThemeColorFromCache();
    
    // 监听路由变化
    uni.$on('refreshThemeColor', () => {
      this.refreshThemeColor();
    });
  },
  onShow() {
    this.getCurrentPath();
    // 从缓存中获取主题色
    this.refreshThemeColor();
  },
  beforeDestroy() {
    // 移除事件监听
    uni.$off('refreshThemeColor');
  },
  computed: {
    // 计算实际使用的主题色
    actualThemeColor() {
      return this.cachedThemeColor || this.themeColor;
    }
  }
};
</script>

<style lang="scss">
.page-container {
  min-height: 100vh;
  box-sizing: border-box;
  position: relative;
}

.custom-tabbar {
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: space-around;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  z-index: 999;
  backdrop-filter: blur(10px);
  border-radius: 50rpx;
  transition: all 0.3s ease;
  
  .tabbar-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    position: relative;
    overflow: hidden;
    
    &.active {
      .tabbar-icon {
        transform: translateY(-4rpx);
      }
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 4rpx;
        background-color: currentColor;
        border-radius: 2rpx;
        opacity: 0.6;
      }
    }
    
    .tabbar-icon {
      margin-bottom: 4rpx;
      transition: transform 0.2s ease;
    }
    
    .tabbar-text {
      font-size: 22rpx;
      transition: color 0.2s ease;
    }
  }
}
</style> 